package cn.anquing.demo.elasticsearch.demo.controller;

import cn.anquing.demo.elasticsearch.demo.es.EsBlogService;
import cn.anquing.demo.elasticsearch.demo.jpa.BlogService;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author wangqq65
 * @since 2021/4/20 13:52
 */

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private BlogService blogService;

    @Resource
    private EsBlogService esBlogService;


    @GetMapping("/hi")
    public Object hello(){

        return "helloWorld";
    }

    @GetMapping("/blog/{id}")
    public Object blog(@PathVariable("id") Long id){
        return  blogService.getById(id);
    }

    @GetMapping("/esBlog/{id}")
    public Object esBlog(@PathVariable("id") Long id){
        return  esBlogService.getById2(id);
    }

    @GetMapping("/search")
    public Object search(String type,String keyword){

        if ((keyword == null || keyword == "") && (type == null || type == "")){
            return "请传入参数：?type=es|mysql&keyword={关键字}";
        }

        if (keyword == null || keyword == "") {
            return "搜索关键字不能为空，参数keyword";
        }

        StopWatch watch = new StopWatch();
        HashMap<String, Object> map = new HashMap<>();
        watch.start();
        if ("es".equals(type)) {
            map.put("result",esBlogService.searchByKeyword2(keyword)) ;
        }else if ( "mysql".equals(type)){
            map.put("result",blogService.searchByKeyword(keyword)) ;

        }else {
            map.put("result","查询方式不正确，type = es | mysql") ;
        }
        watch.stop();
        map.put("time",watch.getTotalTimeMillis());

        return map;

    }
}
